/*
 * @Author: asushiye
 * @Date: 2020-07-06 13:44:51
 * @Commit: file content
 */
import { HttpEventType, HttpEvent, HttpResponse } from '@angular/common/http';
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AfMessageService, AfUpDownService } from '@core';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';

import { CodeGenService } from '../../codegen.service';

@Component({
  selector: 'app-cg-upload',
  templateUrl: './cg-upload.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CgUploadComponent implements OnInit {
  public uploadProgress = 0;
  isLoading = false;
  form: FormGroup;
  title = '';
  record: any;
  constructor(
    private codegen: CodeGenService,
    private modal: NzModalRef,
    private fb: FormBuilder,
    private updown: AfUpDownService,
    private msg: AfMessageService,
    private cdr: ChangeDetectorRef
  ) {
    this.form = this.fb.group({
      extendedFields: [''],
      file: [null, [Validators.required]]
    });
  }

  ngOnInit(): void {
    this.title = `上传${this.record.title}`;
  }

  submit(selected: any) {
    if (Array(selected.files).length <= 0) {
      return;
    }
    const url = this.codegen.getUploadUrl(this.record, this.form.controls['extendedFields'].value);
    this.uploadProgress = 0;
    this.isLoading = true;
    try {
      const fileName = selected.files[0].name;
      this.updown.uploadFilesByMultPart(url, selected.files).subscribe(event => {
        this.cdr.detectChanges();
        // this.uploadProgress = this.getEventMessage(event, selected.files[0]);
        switch (event.type) {
          case HttpEventType.Sent:
            this.msg.notice_info(`开始上传`, `${fileName}文件大小为${selected.files[0].size}`);
            return;
          case HttpEventType.UploadProgress:
            if (event.total !== undefined) {
              this.uploadProgress = Math.round((100 * event.loaded) / event.total);
            }
            this.msg.notice_info(`上传中`, `${fileName}文件${this.uploadProgress}% 已上传`);
            return;
          case HttpEventType.Response:
            // completely uploaded
            if (event instanceof HttpResponse) {
              if (event.ok) {
                const body = event.body as any;
                if (body.status) {
                  this.msg.notice_info(`上传完成`, `${fileName}上传成功`);
                  this.modal.close('ok');
                } else {
                  if (body.code === -2) {
                    this.msg.notice_info(`文件已存在`, `若想上传, 可修改文件名或归档此文件`);
                    this.modal.close('exist');
                  } else {
                    this.msg.notice_info(`上传失败`, `文件异常或网络不稳定，请检查后再重新上传`);
                  }
                }
              }
            }
            return;
          default:
            // other event.type
            this.msg.console_error(`File "${fileName}" surprising upload event: ${event.type}.`);
            return;
        }
      });
    } finally {
      setTimeout(() => {
        this.isLoading = false;
        this.cdr.detectChanges();
      }, 100);
    }
  }

  change(selected: any) {
    this.uploadProgress = 0;
    for (const file of selected.files) {
      console.log(file.name);
    }
  }

  close() {
    this.modal.destroy();
  }
}
